package com.group.transaction.config;

import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author YunXing Pang
 * @date 2019/7/28
 */
@Configuration
public class ShiroConfig {
    /**
     * 创建realm
     *
     * @return realm对象
     */
    @Bean
    public CustomRealm customRealm() {
        return new CustomRealm();
    }

    /**
     * 创建自定义sessionManager对象
     *
     * @return  自定义sessionManager对象
     */
//    @Bean
//    public SessionManager sessionManager() {
//        return new CustomSessionManager();
//    }

    /**
     * 创建scurityManager
     *
     * @return securityManager对象
     */
    @Bean
    public SecurityManager securityManager() {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
//        defaultWebSecurityManager.setSessionManager(sessionManager());
        defaultWebSecurityManager.setRealm(customRealm());
        return defaultWebSecurityManager;
    }

    /**
     * 配置shiroFilterFactoryBean过滤器工厂
     *
     * @param securityManager securityManager对象
     * @return shiroFilterFactoryBean对象
     */
    @Bean
    public ShiroFilterFactoryBean shiroFilter(SecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        // 设置securityManager
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        // 设置需要登录的接口，如果是前后端分离返回json数据接口，如果是单体应用直接跳转页面
        shiroFilterFactoryBean.setLoginUrl("/user/login");
        // 登录成功接口，如果是前后端分离这个接口不存在
        shiroFilterFactoryBean.setSuccessUrl("/");
        // 配置路径对应过滤器，按顺序加载
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        // 匿名访问路径，即游客
//        filterChainDefinitionMap.put("/user/register", "anon");
//        filterChainDefinitionMap.put("/user/login", "anon");
        // 配置全局路径
//        filterChainDefinitionMap.put("/**", "authc");
        filterChainDefinitionMap.put("/**", "anon");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionMap);

        return shiroFilterFactoryBean;
    }
}
